interface TreeNode {
  parent: string;
  title: string;
  key: string;
  children?: TreeNode[];
}

export const Array2Tree = (datas: TreeNode[] = []) => {
  const rootArr: TreeNode[] = [];

  const eventloop = (parent: any) => {
    datas.forEach((element, i) => {
      if (element.parent === parent._id) {
        const now = datas.splice(i, 1)[0];
        parent.children.push(now);
        // 如果剩下数组存在剔除数据id为父，则开始递归
        if (datas.some((d) => d.key === now.key)) {
          eventloop(now);
        }
      }
    });
  };

  datas.forEach((element, i) => {
    // 初步筛选一级节点
    if (!element.parent) {
      const now = datas.splice(i, 1)[0];
      rootArr.push(now);
    }
  });
  rootArr.forEach((data) => {
    eventloop(data);
  });
  return rootArr;
};
